
import redis

'''
 * RedisUtil Redis工具类
 * @description: Redis工具类，封装了Redis操作方法，可根据需求扩展操作方法
 *  
'''
class RedisUtil:

    # 初始化RedisUtil，支持通过URL或主机、端口、密码方式连接Redis
    def __init__(self, url, host, port, pwd, max_connections=10, socket_timeout=10, socket_connect_timeout=5):
        if url:
            self.redis_client = redis.StrictRedis().from_url(url, max_connections=max_connections, socket_timeout=socket_timeout, socket_connect_timeout=socket_connect_timeout)
        else:
            self.redis_client = redis.StrictRedis(host=host, port=port, password=pwd, max_connections=max_connections, socket_timeout=socket_timeout, socket_connect_timeout=socket_connect_timeout)

    # 通过URL方式连接Redis
    @classmethod
    def from_url(cls, url, max_connections=10, socket_timeout=10, socket_connect_timeout=5):
        return cls(url = url, host=None, port=None, pwd=None, max_connections=max_connections, socket_timeout=socket_timeout, socket_connect_timeout=socket_connect_timeout)
 
    # 通过主机、端口、密码方式连接Redis
    @classmethod
    def from_config(cls, host, port, pwd, max_connections=10, socket_timeout=10, socket_connect_timeout=5):
        return cls(url = None, host=host, port=port, pwd=pwd, max_connections=max_connections, socket_timeout=socket_timeout, socket_connect_timeout=socket_connect_timeout)

    def set(self, key, value):
        self.redis_client.set(key, value)

    # 获取Redis中的值，并将其转换为字符串类型
    def get(self, key):
        redis_value = self.redis_client.get(key)
        if redis_value is None or redis_value == '':
            return ''
        return self.redis_client.get(key).decode('utf-8')
    
    # 删除Redis中的值，生产环境通常会禁止通过delete命令删除Redis中的值，因此通过设置超时时间的方式来删除
    def delete(self, key):
        self.redis_client.expire(key, 1)

    def exists(self, key):
        return self.redis_client.exists(key)
    
    def expire(self, key, time):
        self.redis_client.expire(key, time)

    